//@author A0081229H
package storage;
import flexiCommands.Clock;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

public class Maintenance extends Thread {
	Timer timer;
	TimerTask task;
	Storage storage;
	ArrayList<Task> tasks;

	private class MaintainOverdue extends TimerTask {
		@Override
		public void run() {
			// get current system time
			try {
				Date currentDate = Clock.getCurrentDate();
				Time currentTime = Clock.getCurrentTime();
				for (Iterator<Task> it = storage.iterator(); it.hasNext();) {
					Task cTask = it.next();
					Date lastDate = cTask.getDateRange().getEndDate();
					Time lastTime = cTask.getTimeRange().getEndTime();
					if (cTask.getDoneStatus() == false) {
						if (!lastDate.isEmpty()) {
							if (currentDate.compareTo(lastDate) == 1) {
								cTask.setOverdue();
							} else if (currentDate.compareTo(lastDate) == 0) {
								if (currentTime.compareTo(lastTime) == 1) {
									cTask.setOverdue();
								}
							}
						}
					}
				}
			} 		 catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public Maintenance() throws NumberFormatException, Exception {
		timer = new Timer();
		task = new MaintainOverdue();
		storage = Storage.getInstance();
		tasks = new ArrayList<Task>();
	}

	@Override
	public void run() {
		timer.scheduleAtFixedRate(task, 3000, 60000);
	}
}
